﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.SignalR.Client;
using System.ComponentModel.DataAnnotations;
using TrackSystem.Entities.Dtos.Slave;
using TrackSystem.Entities.RequestFeature;

namespace TrackSystem.UI.Server.Pages.Configuration;

public partial class SlaveDef
{
    private List<SlaveDto> _listSlaves;

    private string _sMsg;

    [Required]
    private HubConnection hub;

    [Required]
    private PageParameter? pageOptions = new PageParameter()
    {
        CurrentPage = 1,
        PageSize = 1,
        Filter = ""
    };


    private bool changedStatus = false;
    private IEnumerable<SelectedItem> _regNames = [];

    /// <summary>
    /// 初始化函数
    /// </summary>
    /// <param name="firstRender"></param>
    /// <returns></returns>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await SignalServer();
        }
    }

    /// <summary>
    /// 获取所有逻辑表达式
    /// </summary>
    /// <returns></returns>
    private async Task SignalServer()
    {
        try
        {
            if (hub is null || hub.State == HubConnectionState.Disconnected)
            {
                // 建立SIGNALR连接
                hub = new HubConnectionBuilder()
                    .WithUrl("http://localhost:5000/slavehub")
                    .WithAutomaticReconnect([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3)])
                    .Build();

                await hub.StartAsync();
            }

            // 发送请求
            hub.On<List<SlaveDto>>("ReceiveAllSlave", async (result) =>
            {
                _listSlaves = result;
                _sMsg = $"{DateTime.Now} 收到所有的从站信息";
                if (result.Count > 0)
                {
                    pageOptions.TotalPages = result.Count;
                    pageOptions.CurrentPage = (pageOptions.CurrentPage < result.Count) ? pageOptions.CurrentPage : result.Count;
                }
                else
                {
                    pageOptions.TotalPages = 0;
                    pageOptions.CurrentPage = -1;
                }

                await InvokeAsync(StateHasChanged);
            });

            await hub.SendAsync("GetAllAsync");
        }
        catch (Exception ex)
        {
            _sMsg = ex.Message;
            await InvokeAsync(StateHasChanged);
        }
    }


    private Task BtnNewSlave()
    {
        return Task.FromResult(0);
    }

    private Task BtnDeleteSlave()
    {
        return Task.FromResult(0);
    }

    private async Task BtnEnterChanged()
    {
        try
        {
            if (hub.State == HubConnectionState.Connected)
            {
                hub.On<List<string>>("RevVarNames", async (tt) =>
                {
                    _regNames = tt.Select(c => new SelectedItem(c, c)).ToList();
                    changedStatus = true;
                    await InvokeAsync(StateHasChanged);
                });

                await hub.SendAsync("GetVarNames");
                _sMsg = "";
            }
        }
        catch (Exception ex)
        {
            _sMsg = DateTime.Now.ToString() + ex.Message;
            await InvokeAsync(StateHasChanged);
        }
    }

    private Task BtnCancel()
    {
        changedStatus = false;
        return Task.FromResult(0);
    }

    private Task BtnSave()
    {
        changedStatus = false;
        return Task.FromResult(0);
    }


    /// <summary>
    /// 翻页
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <returns></returns>
    private async Task OnPageClick(int pageIndex)
    {
        pageOptions.CurrentPage = pageIndex;
        await InvokeAsync(StateHasChanged);
    }
}
